package shop.ynubeggar.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import shop.ynubeggar.interceptor.LoginInterceptor;
import shop.ynubeggar.mapper.UserMapper;
import shop.ynubeggar.model.dataobject.UserDO;
import shop.ynubeggar.model.valueobject.LoginUser;
import shop.ynubeggar.service.FileService;
import shop.ynubeggar.utils.ImageUtils;
import shop.ynubeggar.utils.oss.MinioTemplate;
import shop.ynubeggar.utils.oss.OssFile;

import javax.annotation.Resource;

@Slf4j
@Service
public class FileServiceImpl implements FileService {

    @Resource
    MinioTemplate minioTemplate;

    @Resource
    UserMapper userMapper;

    @Override
    public OssFile uploadUserHeadImg(String base64) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();

        // base64转文件
        MultipartFile multipartFile = ImageUtils.base64ToMultipartFile(base64);

        // 存文件到oss
        OssFile ossFile = minioTemplate.putObject(multipartFile);

        // 查找旧文件路径并删除
        UserDO userDO = userMapper.selectById(loginUser.getId());

        String oldOssFile = userDO.getHeadImg();
        if (oldOssFile != null) {
            minioTemplate.removeObject(oldOssFile);
        }

        // 设置新路径并保存
        userDO.setHeadImg(ossFile.getOssFilePath());
        userMapper.updateById(userDO);

        log.info("update headImg success, user: {}", loginUser.getId());
        return ossFile;
    }
}
